﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Kunlun.BusinessLogic
{
    public static class FileMD5
    {
        public static string MD5(string filepath)
        {
            string result = string.Empty;
            try
            {
                FileStream get_file = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] imageFile = new byte[get_file.Length];
                get_file.Read(imageFile, 0, (int)get_file.Length);//将文件流读取到Buffer中
                get_file.Close();
                result = MD5Buffer(imageFile, 0, imageFile.Length);//对Buffer中的字节内容算MD5
                result = MD5String(result);                
            }
            catch (Exception ex)
            {
                WebLog.ErrorLog(ex);
            }
            return result;
        }
        private static string MD5Buffer(byte[] pdfFile, int index, int count)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash_byte = get_md5.ComputeHash(pdfFile, index, count);

            string result = System.BitConverter.ToString(hash_byte);
            result = result.Replace("-", "");
            return result;
        }
        private static string MD5String(string str)
        {
            byte[] MD5Source = System.Text.Encoding.ASCII.GetBytes(str);
            return MD5Buffer(MD5Source, 0, MD5Source.Length);

        }
    }
}
